package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.entity.UpdateArticleMessage;
import com.heima.behavior.service.IReadService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ReadServiceImpl implements IReadService {


    @Value("${topic.read_behavior}")
    private String ReadTopic;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 阅读行为记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRead(ReadBehaviorDto dto) {
        //创建ApReadBehavior表
        ApReadBehavior behavior=new ApReadBehavior();
        User user = MediaThreadLocalUtil.get();
        if (user!=null){
            behavior.setUserId(user.getUserId());
        }else {
            behavior.setEquipmentId(dto.getEquipmentId());
        }
        behavior.setArticleId(dto.getArticleId());
        behavior.setCount(1);
        behavior.setReadDuration(dto.getReadDuration());
        behavior.setPercentage(dto.getPercentage());
        behavior.setLoadDuration(dto.getLoadDuration());
        behavior.setCreatedTime(new Date());
        //查询当前用户或者设备对当前文章是否有历史记录
        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (user==null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        //如果没有,新增
        if (one==null){
            mongoTemplate.save(behavior);
        }else {
            //如果有 更新

            // 每次将阅读记录+1   1秒内 有100个用户同时阅读  加入数据库原本阅读量是1  应该更新到101
            // one.setCount(one.getCount()+1); 这种方式不是原子操作
            Update update=new Update();
            update.inc("count");//相当于 count=count+1
            update.set("readDuration",dto.getReadDuration());
            update.set("percentage",dto.getPercentage());
            update.set("loadDuration",dto.getLoadDuration());
            update.set("updatedTime",new Date());
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
        }

        //发信息到kafka
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(0);
        message.setAdd(1);
        message.setArticleId(dto.getArticleId());
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(ReadTopic,value);

        return ResponseResult.okResult();
    }
}
